package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.dao.LagouUserDao;
import com.lagou.edu.fiegn.CodeServiceFeign;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.pojo.LagouUser;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;
import java.util.UUID;

@Service
public class LagouUserServiceImpl /*implements LagouUserService */{

    @Resource
    LagouUserDao lagouUserDao;

    @Resource
    CodeServiceFeign codeServiceFeign;

    @Resource
    LagouTokenDao lagouTokenDao;

//
//    @Override
    public int register(String email, String password, String code) {
        if(isRegistered(email)){
            return 1;
        }
        int validate = codeServiceFeign.validate(email, code);
        if(validate !=0){
            return validate;
        }
        lagouUserDao.save(LagouUser.builder().email(email).password(password).build());
        return 0;
    }
//
//    @Override
    public boolean isRegistered(String email) {
        return lagouUserDao.findOne(Example.of(LagouUser.builder().email(email).build())).orElse(null)!=null;
    }
//
//    @Override
    public LagouToken login(String email, String password) {
        Example<LagouUser> example = Example.of(LagouUser.builder().email(email).password(password).build());
        LagouUser lagouUser = lagouUserDao.findOne(example).orElse(null);
        if(lagouUser==null){
            return null;
        }
        LagouToken lagouToken = LagouToken.builder().email(email).token(UUID.randomUUID().toString()).build();
        lagouTokenDao.save(lagouToken);
        return lagouToken;
    }
//
//    @Override
    public String info(String token) {
        Optional<LagouToken> optional = lagouTokenDao.findOne(Example.of(LagouToken.builder().token(token).build()));
        return optional.map(t->t.getEmail()).orElse(null);
    }
}
